//
//  LKChooseProductDetailViewController.m
//  YLHelper
//
//  Created by she1323 on 2018/5/3.
//  Copyright © 2018年 she1323. All rights reserved.
//

#import "LKChooseProductDetailViewController.h"
#import "LKChooseProductDetailCell.h"
#import "LKSearchBar.h"
#import "GSFilterView.h"
#import "LKOrderEditBottomView.h"
#import "LKChooseProductViewModel.h"
#import "LKWriteAppointMessageViewController.h"
#import "LKCustomerAppointmentViewController.h"
@interface LKChooseProductDetailViewController ()<UITableViewDataSource,UITableViewDelegate,DKFilterViewDelegate,UISearchBarDelegate>
@property(nonatomic,strong)LKBaseTableview *tableview;
@property(nonatomic,strong)UIView *topView;
@property(nonatomic,strong) LKSearchBar *searchBar;
@property (nonatomic,strong) UIView *bgView;
@property(nonatomic,strong)GSFilterView *filterView;
@property (nonatomic, strong) LKChooseProductViewModel *filterViewModel;
@property(nonatomic,strong)NSMutableArray *datalistArray;
@property(nonatomic,assign)NSInteger PageIndex;
@property(nonatomic,assign)NSInteger MaxResultCount;
@property(nonatomic,copy)NSString *payCategory;
@property(nonatomic,copy)NSString *productTerm;
@property(nonatomic,copy)NSString *yieldFrom;
@property(nonatomic,copy)NSString *yieldTo;
@property(nonatomic,copy)NSString *productCategory;

@end

@implementation LKChooseProductDetailViewController
- (LKChooseProductViewModel *)filterViewModel
{
    if (!_filterViewModel) {
        _filterViewModel = [[LKChooseProductViewModel alloc] init];
        
    }
    return _filterViewModel;
}

-(LKBaseTableview *)tableview{
    if (!_tableview) {
        _topView = [[UIView alloc] initWithFrame:CGRectMake(0, NAVIGATION_BAR_HEIGHT, WIDTH, 46)];
        _topView.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:_topView];
        //创建searchBar
        LKSearchBar *searchBar = [[LKSearchBar alloc] initWithFrame:CGRectMake(8, 8, WIDTH - 16, 30)];
        //默认提示文字
        searchBar.placeholder = @"输入产品信息";
            searchBar.delegate = self;
//        searchBar.showsCancelButton = YES;
        [_topView addSubview:searchBar];
        _tableview = [LKBaseTableview setTableviewWithFrame:CGRectMake(0, NAVIGATION_BAR_HEIGHT + 46, WIDTH, HEIGHT - NAVIGATION_BAR_HEIGHT - 46) style:UITableViewStylePlain registercellClasss:@[@"LKChooseProductDetailCell"]];
        _tableview.delegate = self;
        _tableview.dataSource = self;
        _tableview.backgroundColor = [UIColor whiteColor];
        _tableview.emptyDataSetDelegate = self;
        _tableview.emptyDataSetSource = self;
    }
    return _tableview;
}
/**
 头部下拉刷新
 */
-(void)headerReloadData{
    self.PageIndex = 1;
    self.MaxResultCount = 30;
    NSString *pageIndexStr = [NSString stringWithFormat:@"%ld",self.PageIndex];
    NSString *maxRsult = [NSString stringWithFormat:@"%ld",self.MaxResultCount];
    if (self.IsAppoint) {
        NSDictionary *param = @{@"PageIndex":pageIndexStr,@"MaxResultCount":maxRsult,@"IdentityId":self.customerModel.identityId};
        [self getAppointProductListWithDictonry:param];
    }else if (self.IsAddOrder){
        self.PageIndex = 1;
        self.MaxResultCount = 30;
        NSString *pageIndex = [NSString stringWithFormat:@"%ld",self.PageIndex];
        NSString *maxResult = [NSString stringWithFormat:@"%ld",self.MaxResultCount];
        NSDictionary *param = @{@"PageIndex":pageIndex,@"MaxResultCount":maxResult,@"ProductCategory":@"-1",@"PayCategory":@"-1",@"productName":@""};
        [self getAddOrderProductListWithProductNameWithDictionry:param];
    }
}

/**
 尾部上拉加载更多
 */
-(void)footerReloadData{
    self.PageIndex++;
    self.MaxResultCount = 30;
    NSString *pageIndexStr = [NSString stringWithFormat:@"%ld",self.PageIndex];
    NSString *maxRsult = [NSString stringWithFormat:@"%ld",self.MaxResultCount];
    if (self.IsAppoint) {
        NSDictionary *param = @{@"PageIndex":pageIndexStr,@"MaxResultCount":maxRsult,@"IdentityId":self.customerModel.identityId};
        [self getAppointProductListWithDictonry:param];
    }else if (self.IsAddOrder){
        NSString *pageIndex = [NSString stringWithFormat:@"%ld",self.PageIndex];
        NSString *maxResult = [NSString stringWithFormat:@"%ld",self.MaxResultCount];
        NSDictionary *param = @{@"PageIndex":pageIndex,@"MaxResultCount":maxResult,@"ProductCategory":@"-1",@"PayCategory":@"-1",@"productName":@""};
        [self getAddOrderProductListWithProductNameWithDictionry:param];
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.tableview];
    self.PageIndex = 1;
    self.MaxResultCount = 10;
    NSString *pageIndexStr = [NSString stringWithFormat:@"%ld",self.PageIndex];
    NSString *maxRsult = [NSString stringWithFormat:@"%ld",self.MaxResultCount];
    self.tableview.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerReloadData)];
    self.tableview.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerReloadData)];
    if (self.IsAppoint) {
    NSDictionary *param = @{@"PageIndex":pageIndexStr,@"MaxResultCount":maxRsult,@"IdentityId":self.customerModel.identityId};
        [self getAppointProductListWithDictonry:param];
    }else if (self.IsAddOrder){
        self.PageIndex = 1;
        self.MaxResultCount = 30;
        NSString *pageIndex = [NSString stringWithFormat:@"%ld",self.PageIndex];
        NSString *maxResult = [NSString stringWithFormat:@"%ld",self.MaxResultCount];
        NSDictionary *param = @{@"PageIndex":pageIndex,@"MaxResultCount":maxResult,@"ProductCategory":@"-1",@"PayCategory":@"-1",@"productName":@""};
        [self getAddOrderProductListWithProductNameWithDictionry:param];
    }
   
//    self.tableview.estimatedRowHeight = 200;
    // Do any additional setup after loading the view.
}
-(void)setNavgationBackBtn{
    [super setNavgationBackBtn];
    self.navigationItem.title = @"选择产品";
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightBtn setImage:[UIImage imageNamed:@"loudou"] forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(choice) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
}
-(void)choice{
    if (!_bgView) {
        _bgView = [[UIView alloc] initWithFrame:CGRectMake(0, NAVIGATION_BAR_HEIGHT, WIDTH, HEIGHT - NAVIGATION_BAR_HEIGHT)];
        _bgView.backgroundColor = [UIColor colorWithRed:70.0f/255.0f green:70.0f/255.0f  blue:70.0f/255.0f  alpha:0.4];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(cancelShaixuan:)];
        [_bgView addGestureRecognizer:tap];

    }
    [self.view addSubview:_bgView];
    self.filterView = [[GSFilterView alloc] init];
    [self.bgView addSubview:self.filterView];

    [self.filterView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(self.bgView);
        make.top.mas_equalTo(self.bgView);
        make.height.mas_equalTo(400);
    }];
    UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc] init];
    [self.filterView addGestureRecognizer:tap1];
    self.filterView.delegate = self;
    LKOrderEditBottomView *bottomview = [[[NSBundle mainBundle] loadNibNamed:@"LKOrderEditBottomView" owner:self options:nil] lastObject];
    [bottomview.forwardBtn setTitle:@"重置" forState:UIControlStateNormal];
    [bottomview.forwardBtn addTarget:self action:@selector(resetAction:) forControlEvents:UIControlEventTouchUpInside];
    [bottomview.nextBtn addTarget:self action:@selector(sureAction:) forControlEvents:UIControlEventTouchUpInside];
    [bottomview.nextBtn setTitle:@"确认" forState:UIControlStateNormal];
    [self.bgView addSubview:bottomview];
    [bottomview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.bgView);
        make.top.equalTo(self.filterView.mas_bottom).offset(45);
        make.height.mas_equalTo(68);
    }];
    UIView *middleView = [[UIView alloc] init];
    middleView.backgroundColor = [UIColor whiteColor];
    [self.bgView addSubview:middleView];
    [middleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.bgView);
        make.top.equalTo(self.filterView.mas_bottom);
        make.bottom.equalTo(bottomview.mas_top);
    }];
    CALayer *topLayer = [CALayer layer];
    topLayer.frame = CGRectMake(0, 0, WIDTH, 1);
    topLayer.backgroundColor = cellHeaderBgColor.CGColor;
    [middleView.layer addSublayer:topLayer];
    CALayer *bottomLayer = [CALayer layer];
    bottomLayer.frame = CGRectMake(0, 0, WIDTH, 1);
    bottomLayer.backgroundColor = cellHeaderBgColor.CGColor;
    [bottomview.layer addSublayer:bottomLayer];
    [self.filterView setFilterModels:self.filterViewModel.fundModels];
}
-(void)cancelShaixuan:(UITapGestureRecognizer *)tap{
    
    UIView *view = tap.view;
    [view removeFromSuperview];
}

/**
 筛选重置按钮的点击事件

 @param btn an
 */
-(void)resetAction:(UIButton *)btn{
    [self.filterView choiceAgain];
}

/**
 筛选确认按钮的点击事件

 @param btn btn
 */
-(void)sureAction:(UIButton *)btn{
    NSLog(@"%@",self.filterViewModel.fundModels);
    for (NSInteger i = 0; i < self.filterViewModel.fundModels.count; i++) {
        DKFilterModel *model = self.filterView.filterModels[i];
        NSArray *arra = [model getFilterResult];
        NSString *str = [arra firstObject];
        if (i == 0) {
            self.payCategory = [str isEqual:@"不限"] ? @"-1":str;
        }
        if (i == 1) {
            NSString *lalStr = [str isEqual:@"不限"] ? @"-1":str;
            if ([lalStr isEqual:@"-1"]) {
                self.yieldFrom = @"-1";
                self.yieldTo = @"-1";
            }else{
                self.yieldFrom = [[lalStr componentsSeparatedByString:@"-"] firstObject];
                self.yieldTo = [[lalStr componentsSeparatedByString:@"-"] lastObject];
            }
        }
        if (i == 2) {
            self.productTerm = [str isEqual:@"不限"] ? @"-1":[[str componentsSeparatedByString:@"个"] firstObject];
        }
        if (i == 3) {
            self.productCategory = [str isEqual:@"不限"] ? @"-1":str;
        }
        NSLog(@"选中的字符串%@",str);
        
    }
    self.PageIndex = 1;
    self.MaxResultCount = 30;
    NSString *pageIndex = [NSString stringWithFormat:@"%ld",self.PageIndex];
    NSString *maxResult = [NSString stringWithFormat:@"%ld",self.MaxResultCount];
    NSDictionary *param = @{@"PageIndex":pageIndex,@"MaxResultCount":maxResult,@"ProductCategory":self.productCategory,@"PayCategory":self.payCategory,@"productName":@"",@"YieldFrom":self.yieldFrom,@"YieldTo":self.yieldTo,@"ProductTerm":self.productTerm};
     [self getAddOrderProductListWithProductNameWithDictionry:param];
    [self.bgView removeFromSuperview];
    [self.filterView removeFromSuperview];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.datalistArray.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    LKChooseProductDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LKChooseProductDetailCell"];
    cell.appointmodel = self.datalistArray[indexPath.section];
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 130;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headerView = [[UIView alloc] init];
    headerView.backgroundColor = cellHeaderBgColor;
    return headerView;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 12;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [[UIView alloc] init];
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.00000000001;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.IsAppoint) {
        LKWriteAppointMessageViewController *vc = [[LKWriteAppointMessageViewController alloc] init];
        vc.productmodel = self.datalistArray[indexPath.section];
        vc.customermodel = self.customerModel;
        [self.navigationController pushViewController:vc animated:YES];
        
    }
    if (self.IsAddOrder) {
        LKProductModel *model = self.datalistArray[indexPath.section];
        [self judegeIsAppointProductAccordingIdentityId:_customerModel AdnProductId:model];
//        if (self.productmodelBlock) {
//            self.productmodelBlock(self.datalistArray[indexPath.section]);
//            [self.navigationController popViewControllerAnimated:YES];
//        }
    }
}

/**
 判断身份-产品是否已经预约

 */
-(void)judegeIsAppointProductAccordingIdentityId:(LKCustomerModel *) customerModel AdnProductId:(LKProductModel *)productModel{
    NSDictionary *param;
    if (self.isOrderUpdate) {
        param = [NSDictionary dictionaryWithObjectsAndKeys:self.identId,@"IdentityId",productModel.productId,@"ProductId", nil];
    }else{
        param = [NSDictionary dictionaryWithObjectsAndKeys:customerModel.identityId,@"IdentityId",productModel.productId,@"ProductId", nil];
    }
    
    [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerlUrl apiPath:judgeProductAppointUrl header:[LKUserInforTool header] parameters:param progress:^(NSProgress * _Nullable progress) {
        
    } success:^(BOOL isSuccess, id  _Nullable responseObject) {
        NSString *value = responseObject[@"result"][@"isNeetReservation"];
        if ([value integerValue]) {
            if ([responseObject[@"result"][@"isAllow"] integerValue]) {
                if (self.productmodelBlock) {
                    self.productmodelBlock(productModel);
                    [self.navigationController popViewControllerAnimated:YES];
                }
            }else{
                LKCustomerAppointmentViewController *vc = [[LKCustomerAppointmentViewController alloc] init];
                vc.model = self.customerModel;
                vc.isOrderUpdate = self.isOrderUpdate;
                vc.customerId = self.customeId;
                [self.navigationController pushViewController:vc animated:YES];
                
            }
        }else{
            if (self.productmodelBlock) {
            self.productmodelBlock(productModel);
                [self.navigationController popViewControllerAnimated:YES];
        }
        }
    } failure:^(NSString * _Nullable errorMessage) {
        
    }];
}
/**
 获取预约产品列表
 */
-(void)getAppointProductListWithDictonry:(NSDictionary *)param{
    [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerlUrl apiPath:getAppointmentProductUrl header:[LKUserInforTool header] parameters:param progress:^(NSProgress * _Nullable progress) {
        
    } success:^(BOOL isSuccess, id  _Nullable responseObject) {
        [self.tableview.mj_header endRefreshing];
        [self.tableview.mj_footer endRefreshing];
        if (self.PageIndex == 1) {
            [self.datalistArray removeAllObjects];
        }
        NSArray *itemsArra = responseObject[@"result"][@"items"];
        for (NSDictionary *dic in itemsArra) {
            LKProductModel *model = [LKProductModel modelWithDictionary:dic];
            [self.datalistArray addObject:model];
        }
//        if (itemsArra.count < self.datalistArray.count) {
//            [self.tableview.mj_footer endRefreshingWithNoMoreData];
//        }
        if (self.datalistArray.count == 0) {
            self.tableview.mj_footer.hidden = YES;
        }
        [self.tableview reloadData];
    } failure:^(NSString * _Nullable errorMessage) {
        
    }];
}

/**
 获取添加订单的产品列表
 */
-(void)getAddOrderProductListWithProductNameWithDictionry:(NSDictionary *)param{
    [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerlUrl apiPath:addOrderOfProductListUrl header:[LKUserInforTool header] parameters:param progress:^(NSProgress * _Nullable progress) {
        
    } success:^(BOOL isSuccess, id  _Nullable responseObject) {
        [self.tableview.mj_header endRefreshing];
        [self.tableview.mj_footer endRefreshing];
        if (self.PageIndex == 1) {
            [self.datalistArray removeAllObjects];
        }
        NSArray *itemsArra = responseObject[@"result"][@"items"];
        for (NSDictionary *dic in itemsArra) {
            LKProductModel *model = [LKProductModel modelWithDictionary:dic];
            [self.datalistArray addObject:model];
        }
//        if (itemsArra.count < self.datalistArray.count) {
//            [self.tableview.mj_footer endRefreshingWithNoMoreData];
//        }
        if (self.datalistArray.count == 0) {
            self.tableview.mj_footer.hidden = YES;
        }
        [self.tableview reloadData];
        
    } failure:^(NSString * _Nullable errorMessage) {
        
    }];
}
-(NSMutableArray *)datalistArray{
    if (!_datalistArray) {
        _datalistArray = [[NSMutableArray alloc] init];
    }
    return _datalistArray;
}
#pragma mark - UISearchBarDelegate
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
    return YES;
}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
        searchBar.showsCancelButton = YES;
}
//-(BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar{
//    searchBar.showsCancelButton = NO;
//
//}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    NSLog(@"SearchButton");
    self.PageIndex = 1;
    self.MaxResultCount = 30;
    NSString *pageIndex = [NSString stringWithFormat:@"%ld",self.PageIndex];
    NSString *maxResult = [NSString stringWithFormat:@"%ld",self.MaxResultCount];
        NSDictionary *param = @{@"PageIndex":pageIndex,@"MaxResultCount":maxResult,@"ProductCategory":@"-1",@"PayCategory":@"-1",@"productName":searchBar.text};
    [self getAddOrderProductListWithProductNameWithDictionry:param];
    [searchBar resignFirstResponder];
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    searchBar.showsCancelButton = NO;
    //    [searchBar setShowsCancelButton:NO animated:YES];
    //    [self.searchBar resignFirstResponder];
        searchBar.text = @"";
    self.PageIndex = 1;
    self.MaxResultCount = 30;
    NSString *pageIndex = [NSString stringWithFormat:@"%ld",self.PageIndex];
    NSString *maxResult = [NSString stringWithFormat:@"%ld",self.MaxResultCount];
    NSDictionary *param = @{@"PageIndex":pageIndex,@"MaxResultCount":maxResult,@"ProductCategory":@"-1",@"PayCategory":@"-1",@"productName":searchBar.text};
    [self getAddOrderProductListWithProductNameWithDictionry:param];
    [searchBar resignFirstResponder];
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{

    NSLog(@"%@",searchText);
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
